<?php
namespace app\common\service\WebSocket\SocketService; 

use app\Normal;
use app\BaseService;
use app\model\BbcModel\BusinessWithdraw;
use app\common\service\OrderService\OrderCheckService;
use app\model\BbcModel\Order;
use app\model\BbcModel\OrderGoods;

class OrderSocketService extends BaseService
{
    public $socket_connector;

    public $fd;

    public $host;
    public $pageLimit      = 2000;
    
    public function orderExport($parameters = []) {
        ini_set('memory_limit', '3096M');
        $this->socket_connector = $parameters['socket'];
        $this->fd               = $parameters['fd'];
        $this->host             = $parameters['host'];
        $data                   = $parameters['requestData'];
        $data['cid']            = $parameters['_master_user']['cid'];
        if($parameters['_master_user']['cb_id']>0){
            $data['cb_id']= $parameters['_master_user']['cb_id'];
        }
        $check= callApi(OrderCheckService::class, 'makeWhere',$data);
        $where=$check['where'];
        $service=$check['service'];
        $business=$check['business'];
        $store=$check['store'];
        $total_count=Order::instance()->alias('o')
            ->join('order_extra oe','oe.order_id=o.id')
            ->where($where)
            ->count();
        $total_page  = ceil($total_count / $this->pageLimit);
        $importData  = [];
        for ($page = 0; $page < $total_page; $page++) {
            $list=Order::instance()->alias('o')
                ->field('o.*,oe.*,oe.id as ex_id')
                ->join('order_extra oe','oe.order_id=o.id')
                ->where($where)
                ->limit($page * $this->pageLimit, $this->pageLimit)
                ->select()
                ->toArray();        
            if ($list) {
                $tmpData = [];                
                foreach ($list as $v) {
                    $pushstatus='';
                    if( $v['push_success'] == 1 && $v['push_pay_success'] == 1) {
                        $pushstatus='推送成功';
                    } elseif($v['push_success']==0) {
                        $pushstatus='订单推送失败';
                    }elseif($v['push_pay_success']==0){
                        $pushstatus='支付单推送失败';
                    }
                    $ordergoods= OrderGoods::instance()->field('goods_name')->where(['order_id'=>$v['id']])->select()->toArray();
                    $goodsname= array_column($ordergoods, 'goods_name');
                    $goodsname= implode(',', $goodsname);
                    $tmpData[] = [
                        $service[$v['sp_id']],
                        $business[$v['cb_id']],
                        $store[$v['mn_sid']]??'',
                        Order::instance()->status[$v['status']],
                        $pushstatus,
                        $v['is_return']>0?'是':'否',
                        Order::instance()->return_status[$v['return_status']],
                        $v['pay_sn'],
                        $v['sn'],
                        $v['price_order'],
                        $v['price_total'],
                        bcadd($v['tax_fee'], $v['post_tax']),
                        $v['price_express'],
                        $v['total_discount'],
                        $v['shop_money'],
                        $v['store_money'],
                        $goodsname,
                        $v['cd']>0?date('Y-m-d H:i:s',$v['cd']):'',
                        $v['pay_time']>0?date('Y-m-d H:i:s',$v['pay_time']):'',
                        $v['shipping_time']>0?date('Y-m-d H:i:s',$v['shipping_time']):'',
                        $v['receive_name'],
                        $v['receive_mobile'],
                        $v['buyer_mobile']
                    ];
                }
                $importData = array_merge($importData, $tmpData);
            }

            if ($page == $total_page - 1) {
                $percent = 98.00; //预留给写文件使用
            } else {
                $percent = bcdiv($page, $total_page - 1, 4);
                $percent = bcmul($percent, 100, 2);
            }

            if ($this->socket_connector) {
                $send = Normal::returnWsStatus(Normal::WS_START, "进行中", [
                    'percent' => $percent,
                ]);
                $send = json_encode($send, JSON_UNESCAPED_UNICODE);
                $this->socket_connector->push($this->fd, $send);
            }
        }
        //数据准备完成开始写入excel本地数据
        $send = Normal::returnWsStatus(Normal::WS_START, "进行中", [
            'percent' => 99.00,
        ]);
        $send = json_encode($send, JSON_UNESCAPED_UNICODE);
        $this->socket_connector->push($this->fd, $send);

        $fileName     = "订单导出";
        $headArr      = $this->getColumns();
        $data         = $importData;
        $download_url = xlsxFileLocalStorage($headArr, $data, $fileName, $this->host);
        return Normal::returnWsStatus(Normal::WS_END, "已完成", [
            'percent'      => 100.00,
            'download_url' => $download_url,
            'name'=>'订单导出'
        ]);
    }
     //excel头部
    public function getColumns() {
        return [
            '服务商',
            '渠道商',
            '店铺',
            '订单状态',
            '推单状态',
            '是否发起售后',
            '售后审核状态',
            '渠道商订单编号',
            '子订单编号',
            '订单金额',
            '商品金额',
            '税金',
            '运费',
            '优惠金额',
            '渠道商佣金',
            '商品名称',
            '创建时间',
            '支付时间',
            '发货时间',
            '收货人姓名',
            '收货人手机号',
            '订购人手机号'
        ];
    }
}
